public class Demo9 {
    public static int count = 0;
    public static void main(String[] args) {
        Object locker = new Object();
        Thread a = new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(1000);
                    synchronized (locker) {
                        while (count % 3 != 2) {
                            try {
                                locker.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }

                        System.out.println(" a");
                        count++;
                        locker.notifyAll();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        Thread b = new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(1000);
                    synchronized (locker) {
                        while (count % 3 != 1) {
                            try {
                                locker.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }

                        System.out.print(" b");
                        count++;
                        locker.notifyAll();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        Thread c = new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(1000);
                    synchronized (locker) {
                        while (count % 3 != 0) {
                            try {
                                locker.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }

                        System.out.print("c");
                        count++;
                        locker.notifyAll();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        a.start();
        b.start();
        c.start();
    }
}
